package xjtu.se.articlecommunity.common.base;


import com.auth0.jwt.exceptions.JWTDecodeException;
import xjtu.se.articlecommunity.common.*;
import xjtu.se.articlecommunity.common.dto.CurrentUser;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter({"/user/*","/message/getNewMessageNumber"})
public class CuserFilter implements Filter {
    private static String[] freePaths = {"gettablist","getfeed","gethot","searchart","info","uploadImg"};

    @Resource
    private CommonService commonService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String path = request.getServletPath();
        System.out.println(path);

        String[] paths = request.getServletPath().split("/");


        if("login".equals(paths[2]) || "register".equals(paths[2])){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        for (int i=0;i<freePaths.length;i++){
            if(paths.length>3 && freePaths[i].equals(paths[3])){
                filterChain.doFilter(servletRequest,servletResponse);
                return;
            }
        }


        String clientToken = request.getHeader("Token");

        try {
            TokenUtils.verifyToken(clientToken,commonService);
            filterChain.doFilter(servletRequest,servletResponse);
        } catch (RuntimeException e){
            e.printStackTrace();
            Utils.outJson(response, Result.fail(Result.ERR_CODE_UNLOGIN,"您尚未登录"));
        }
    }

    @Override
    public void destroy() {

    }
}
